"""
序列化
"""
import time
from random import Random

from rest_framework import serializers

from .models import ShoppingCart, OrderInfo, OrderGoods
from goods.models import Goods
from goods.serializers import GoodsSerializer


class ShoppingCartListSerializer(serializers.ModelSerializer):

    goods = GoodsSerializer(many=False)

    class Meta:
        model = ShoppingCart
        fields = "__all__"


class ShoppingCartSerializer(serializers.Serializer):

    # 获取到当前用户
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )

    # 外键需要设置 queryset 指定范围
    # 没有设置 ModelSerializer 就要设置 queryset
    goods = serializers.PrimaryKeyRelatedField(queryset=Goods.objects.all(), required=True)

    nums = serializers.IntegerField(required=True, min_value=1, error_messages={
        "min_value": "商品数量不能小于1",
        "required": "请填写购买数量"
    })

    add_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M')  # 设置为不可提交，只可获取

    def create(self, validated_data):
        user = self.context['request'].user  # 在 Serializer 中 request 在 context 中，跟 View 中不一样
        nums = validated_data['nums']
        goods = validated_data['goods']

        existed = ShoppingCart.objects.filter(user=user, goods=goods)

        if existed:
            existed = existed[0]
            existed.nums += nums
            existed.save()
        else:
            existed = ShoppingCart.objects.create(**validated_data)

        return existed

    def update(self, instance, validated_data):
        # 直接修改商品的数量
        instance.nums = validated_data["nums"]
        instance.save()
        return instance


class OrderCreateSerializer(serializers.ModelSerializer):

    # 获取到当前用户
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )

    pay_status = serializers.CharField(read_only=True)
    trade_no = serializers.CharField(read_only=True)
    order_sn = serializers.CharField(read_only=True)
    pay_time = serializers.DateTimeField(read_only=True)

    def generate_order_sn(self):
        # 自动生成订单号
        # 规则：当前时间 + user_id + 随机数
        random_ins = Random()
        order_sn = "{time_str}{user_id}{random}".format(time_str=time.strftime("%Y%m%d%H%M%S"),
                                                        user_id=self.context["request"].user.id,
                                                        random=random_ins.randint(10, 99))
        return order_sn

    def validate(self, attrs):
        attrs["order_sn"] = self.generate_order_sn()
        return attrs

    class Meta:
        model = OrderInfo
        fields = "__all__"


class OrderGoodsSerializer(serializers.ModelSerializer):
    goods = GoodsSerializer(many=False)

    class Meta:
        model = OrderGoods
        fields = "__all__"


class OrderListSerializer(serializers.ModelSerializer):
    goods = OrderGoodsSerializer(many=True)

    class Meta:
        model = OrderInfo
        fields = "__all__"
